<?php
namespace TwinPeaks\Core\Http;
use TwinPeaks\Core as Core;

require_once __DIR__ . '/../CUri.php';

/**
 * HTTP URI handler
 */
class CUri extends Core\CUri
{
	// Canonical HTTP scheme names.
	const SCHEME_HTTP_TOKEN = 'http';
	const SCHEME_HTTS_TOKEN = 'https';

	/**
	 * User name as provided in authority of URI
	 * @var null|string
	 */
	protected $user;
	
	/**
	 * Password as provided in authority of URI
	 * @var null|string
	 */
	protected $password;
	
	/**
	 * @var null|string
	 */
	static protected $defaultScheme = self::SCHEME_HTTP_TOKEN;
	
	/**
	 * @return void
	 */
	function __construct()
	{
		$this->setScheme(self::getDefaultScheme());
		$this->setHost(self::getDefaultHost());
	}

	 /**
	 * Get the username part (before the ':') of the userInfo URI part
	 *
	 * @return null|string
	 */
	function getUser()
	{
		if (null !== $this->user)
			return $this->user;

		$this->parseUserInfo();
		return $this->user;
	}
	/**
	 * Get the password part (after the ':') of the userInfo URI part
	 *
	 * @return string
	 */
	function getPassword()
	{
		if (null !== $this->password)
			return $this->password;
		
		$this->parseUserInfo();
		return $this->password;
	}
	/**
	 * Set the username part (before the ':') of the userInfo URI part
	 *
	 * @param  string $user
	 * @return Http
	 */
	function setUser($user)
	{
		$this->user = $user;
		return $this;
	}
	
	/**
	 * Set the password part (after the ':') of the userInfo URI part
	 *
	 * @param  string $password
	 * @return Http
	 */
	function setPassword($password)
	{
		$this->password = $password;
		return $this;
	}
	/**
	 * Validate the host part of an HTTP URI
	 *
	 * This overrides the common URI validation method with a DNS or IP only
	 * default. Users may still enforce allowing other host types.
	 *
	 * @param  string  $host
	 * @param  integer $allowed
	 * @return boolean
	 */
	static function validateHost($host)
	{
		return true;
		return parent::validateHost($host, $allowed);
	}
	
	/**
	 * Parse the user info into username and password segments
	 *
	 * Parses the user information into username and password segments, and
	 * then sets the appropriate values.
	 *
	 * @return void
	 */
	protected function parseUserInfo()
	{
		// No user information? we're done
		if (null === $this->userInfo)
			return;
		// If no ':' separator, we only have a username
		if (false === strpos($this->userInfo, ':'))
			$this->setUser($this->userInfo);
			return;
		// Split on the ':', and set both user and password
		list($user, $password) = explode(':', $this->userInfo, 2);
		$this->setUser($user);
		$this->setPassword($password);
	}
	
	/**
	 * Return the URI port
	 *
	 * @return integer
	 * @see    TwinPeaks\Core\CUri::getPort()
	 */
	function getPort()
	{
		return $this->port;
	}
	
	/**
	 * @return CUrl
	 */
	function getRelativeUrl()
	{
		return parent::getRelativeUri();
	}
	
	/**
	 * @return CUrl
	 */
	function getRelativeUrlNoQuery()
	{
		return parent::getRelativeUriNoQuery();
	}
}
